package org.alps.demo.sentinel.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @date 2021-04-03
 * @author zkw
 */
@RestController
public class IndexController {

    @GetMapping("/flow")
    public String flow() {
        Entry entry = null;
        try {
            //2.1 定义资源名称
            entry = SphU.entry("helloword");
            //2.2 执行资源逻辑代码
            System.err.println("helloworld: 访问数据库");
            System.err.println("helloworld: 访问远程redis");
            System.err.println("helloworld: 数据库持久化操作");
            Thread.sleep(20);

        } catch (BlockException e) {
            System.err.println("要访问的资源被流控了，执行流控逻辑");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
        return "flow";
    }

    int count = 0;

    @GetMapping("/degrade")
    public String degrade() throws Exception {
        count++;
        Entry entry = null;
        try {
            /**
             * resourceName定义：类全路径名:方法名（流控的粒度：方法）
             * 还可以更细粒度的控制：
             * 类全路径名:方法名:selectDB、类全路径名:方法名:selectRedis
             */
            String resourceName = "org.alps.demo.sentinel.controller.IndexController:degrade";
            //2.1 定义资源名称
            entry = SphU.entry(resourceName);
            //2.2 执行资源逻辑代码
            if (count % 2 == 0) {
                Thread.sleep(100);
                //throw new Exception("degrade-->方法抛出自定义异常");
            } else {
                Thread.sleep(20);
                System.err.println("degrade-->方法执行正常");
            }
        } catch (BlockException e) {
            System.err.println("要访问的资源被降级了，执行流控逻辑");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
        return "degrade";
    }


}
